package com.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * @author chenyongjiu
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * 定义一个线程池
     * 通过properties配置线程池参数，只能创建一个默认的ThreadPoolTaskExecutor。如果要创建多个线程池，必须自定义Bean模式创建
     */
    @Bean("taskExecutor")
    public Executor taskExecutor () {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(200);
        //队列长度
        executor.setQueueCapacity(100);
        //线程空闲时间
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        //配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }

    @Bean("taskDiscardExecutor")
    public Executor taskDiscardExecutor () {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        //队列长度
        executor.setQueueCapacity(10);
        //线程空闲时间
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskDiscardExecutor-");
        //配置拒绝策略,会让被线程池拒绝的任务直接抛弃，不会抛异常也不会执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        return executor;
    }
}
